package com.shimao.celnet.payment.service.impl.apiservice;

import com.baiwang.bop.client.BopException;
import com.baiwang.bop.client.IBopClient;
import com.baiwang.bop.client.ILoginClient;
import com.baiwang.bop.client.impl.BopRestClient;
import com.baiwang.bop.client.impl.PostLogin;
import com.baiwang.bop.request.impl.LoginRequest;
import com.baiwang.bop.request.impl.invoice.common.InvoiceDetails;
import com.baiwang.bop.request.impl.invoice.impl.InvoiceOpenRequest;
import com.baiwang.bop.respose.entity.LoginResponse;
import com.shimao.celnet.payment.model.*;
import com.shimao.celnet.payment.model.request.SCodeNameConstant;
import com.shimao.celnet.payment.service.*;
import com.shimao.celnet.payment.service.apiservice.CallOut_invOpenOutService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class CallOut_invOpenOutServiceImpl implements CallOut_invOpenOutService {


    @Autowired(required = false)
    private PInvoiceBlueService pInvoiceBlueService;

    @Autowired(required = false)
    private PInvoiceRedService pInvoiceRedService;

    @Autowired(required = false)
    private PInvoiceBlueDetailService pInvoiceBlueDetailService;

    @Autowired(required = false)
    private PInvoiceRedDetailService pInvoiceRedDetailService;

    @Autowired
    private SCodeNameService sCodeNameService;

    /**
     * 通过百望参数，获取百望token
     *
     * @return
     */
    @Override
    public String getToken() {
        SCodeNameConstant sCodeNameConstant = getBwSettingInfo();
        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setAppkey(sCodeNameConstant.getKey());
        loginRequest.setAppSecret(sCodeNameConstant.getSecret());//"appSecret"
        loginRequest.setUserName(sCodeNameConstant.getUesrName());//"username"
        loginRequest.setPasswordMd5(sCodeNameConstant.getPassWord());//"password"
        loginRequest.setUserSalt(sCodeNameConstant.getSalt());//"UUID"盐值（加盐加密）
        ILoginClient loginClient = new PostLogin(sCodeNameConstant.getRateUrl());
        LoginResponse loginResponse = loginClient.login(loginRequest);
        String token = loginResponse.getAccess_token();//获取token
        System.out.println("==token==" + token);
        return token;
    }

    /**
     * 获取百望连接的客户端
     *
     * @return
     */
    @Override
    public IBopClient getClient() {
        SCodeNameConstant sCodeNameConstant = getBwSettingInfo();
        IBopClient client = new BopRestClient(sCodeNameConstant.getRateUrl(), sCodeNameConstant.getKey(), sCodeNameConstant.getSecret());
        return client;
    }

    /**
     * 通过guid查询开红票记录
     *
     * @param guid
     * @return
     */
    @Override
    public PInvoiceRed getPInvoiceRed(String guid) {
        if (StringUtils.isNotEmpty(guid)) {
            return (PInvoiceRed) pInvoiceRedService.getInfo(guid).get("pInvoiceRed");
        }
        return null;
    }

    /**
     * 通过guid查询开蓝票记录
     *
     * @param guid
     * @return
     */
    @Override
    public PInvoiceBlue getPInvoiceBlue(String guid) {
        if (StringUtils.isNotEmpty(guid)) {
            return (PInvoiceBlue) pInvoiceBlueService.getInfo(guid).get("pInvoiceBlue");
        }
        return null;
    }

    /**
     * 将通过接口传入
     */
    @Override
    public InvoiceOpenRequest makeRequestClass(Map map) {
        InvoiceOpenRequest request = new InvoiceOpenRequest();
        try {
            if (map.get("pInvoiceRed") == null) {
                PInvoiceBlue pInvoiceBlue = (PInvoiceBlue) map.get("pInvoiceBlue");
                request.setSellerTaxNo(pInvoiceBlue.getSellerTaxNo());//销方单位税号
                request.setDeviceType(pInvoiceBlue.getDeviceType());//设备类型 0税控服务器，1税控盘
                request.setOrganizationCode(pInvoiceBlue.getOrganizationCode());
                request.setSerialNo(pInvoiceBlue.getSerialNo());//开票流水号，唯一标志开票请求。支持数字字母下划线组合。
                request.setInvoiceSpecialMark(pInvoiceBlue.getInvoiceSpecialMark());//特殊票种标记，00：普通发票 02：农业发票 默认：00
                request.setInvoiceTypeCode(pInvoiceBlue.getInvoiceTypeCode());//发票种类编码，004:增值税专用发票，007:增值税普通发票，026：增值税电子发票，025：增值税卷式发票
                request.setInvoiceTerminalCode(pInvoiceBlue.getInvoiceYerminalCode());//开票点编码
                request.setBuyerTaxNo(pInvoiceBlue.getBuyerTaxNo() == null ? "" : pInvoiceBlue.getBuyerTaxNo());//购方单位税号,从前台页面传过来的map中获取
                request.setBuyerName(pInvoiceBlue.getBuyerName());//购方单位名称,
                request.setBuyerAddressPhone(pInvoiceBlue.getBuyerAddressPhone() == null ? "" : pInvoiceBlue.getBuyerAddressPhone());//购方地址及电话专票必填
                request.setBuyerBankAccount(pInvoiceBlue.getBuyerBankAccount() == null ? "" : pInvoiceBlue.getBuyerBankAccount());//购方开户行及账号专票必填
                request.setDrawer(pInvoiceBlue.getDrawer());//开票人
                request.setChecker(pInvoiceBlue.getChecker());//复核人
                request.setPayee(pInvoiceBlue.getPayee());//收款人
                request.setInvoiceType(FinalUtil.INVOICE_TYPE_BULE);//开票类型0:正数发票（蓝票） 1：负数发票（红票）
                request.setInvoiceListMark(pInvoiceBlue.getInvoiceListMark());//“清单标志： 0：无清单 1：带清单 （发票明细大于等于8行必须带清单）”
                request.setTaxationMode(pInvoiceBlue.getTaxationMode());//征税方式 0：普通征税，2：差额征税
                request.setDeductibleAmount(pInvoiceBlue.getDeductibleAmount());//扣除额保留两位小数
                request.setInvoiceTotalPriceTax(MyDateUtil.getTxFloat(pInvoiceBlue.getInvoiceTotalPriceTax()));//价税合计，保留两位小数
                request.setSignatureParameter(sCodeNameService.getBWListByType(FinalUtil.CODE_NAME_INVOICE_SIGNATURE_BW).get(0).getCode());//百望所需要的默认签名值
                // request.setInvoiceTotalPrice(MyDateUtil.getTxFloat(pInvoiceBlue.getInvoiceTotalPrice()));//合计金额，保留两位小数
                //  request.setInvoiceTotalTax(MyDateUtil.getTxFloat(pInvoiceBlue.getInvoiceTotalTax()));// 合计税额，保留两位小数
                if (pInvoiceBlue.getDeviceType() == "1") {
                    //设备类型为1税控盘，必填
                    request.setTaxDiskNo(pInvoiceBlue.getTaxDiskNo());//税控盘编号
                    request.setTaxDiskKey(pInvoiceBlue.getTaxDiskKey());//税控盘口令
                    request.setTaxDiskPassword(pInvoiceBlue.getTaxDiskPassword());//税务数字证书密码
                }
                request.setGoodsCodeVersion(pInvoiceBlue.getGoodsCodeVersion());//商品编码版本号
                request.setConsolidatedTaxRate(pInvoiceBlue.getConsolidatedTaxRate());//综合税率
                request.setNotificationNo(pInvoiceBlue.getNotificationNo());//通知单编号
                // System.out.println("1"+ pInvoiceBlue.getHouseName() == null? "" : pInvoiceBlue.getHouseName() + "/" + pInvoiceBlue.getRemarks() == null ? "" : pInvoiceBlue.getRemarks());
                request.setRemarks( pInvoiceBlue.getRemarks() == null ? "" : pInvoiceBlue.getRemarks());//备注
                //查询开票明细数据
                List<PInvoiceBlueDetail> pinvoiceDetailList = pInvoiceBlueDetailService.getByInvoiceGuid(pInvoiceBlue.getGuid());
                List<InvoiceDetails> invoiceDetailsList = new ArrayList<InvoiceDetails>();
                for (PInvoiceBlueDetail pInvoiceDetail : pinvoiceDetailList) {
                    //百望开票明细
                    InvoiceDetails invoiceDetails = new InvoiceDetails();
                    invoiceDetails.setGoodsLineNo(pInvoiceDetail.getGoodsLineNo());//明细行号
                    invoiceDetails.setGoodsLineNature(pInvoiceDetail.getGoodsLineNature());//发票行性质，0：正常行 1：折扣行 2：被折扣行
                    invoiceDetails.setGoodsCode(pInvoiceDetail.getGoodsCode());//国税商品编码
                    invoiceDetails.setGoodsExtendCode(pInvoiceDetail.getGoodsExtendCode());//自定义商品编码
                    invoiceDetails.setGoodsName(pInvoiceDetail.getGoodsName());//自定义商品名称
                    invoiceDetails.setGoodsTaxItem(pInvoiceDetail.getGoodsTaxItem());//国税商品名称
                    invoiceDetails.setGoodsSpecification(pInvoiceDetail.getGoodsSpecification());
                    invoiceDetails.setGoodsUnit(pInvoiceDetail.getGoodsUnit());
                    invoiceDetails.setGoodsQuantity(pInvoiceDetail.getGoodsQuantity());
                    if (!("".equals(pInvoiceDetail.getGoodsPrice()) || pInvoiceDetail.getGoodsPrice() == null)) {
                        invoiceDetails.setGoodsPrice(MyDateUtil.getTxFloat(pInvoiceDetail.getGoodsPrice()));
                    }
                    if (!("".equals(pInvoiceDetail.getGoodsTotalPrice()) || pInvoiceDetail.getGoodsTotalPrice() == null)) {
                        invoiceDetails.setGoodsTotalPrice(MyDateUtil.getTxFloat(pInvoiceDetail.getGoodsTotalPrice()));//金额,单位：元，保留两位小数

                    }
                    if (!("".equals(pInvoiceDetail.getGoodsTotalTax()) || pInvoiceDetail.getGoodsTotalTax() == null)) {
                        invoiceDetails.setGoodsTotalTax(MyDateUtil.getTxFloat(pInvoiceDetail.getGoodsTotalTax()));//税额
                    }
                    invoiceDetails.setGoodsTaxRate(pInvoiceDetail.getGoodsTaxRate());//税率
                    invoiceDetails.setGoodsDiscountLineNo(pInvoiceDetail.getGoodsDiscountLineNo());
                    invoiceDetails.setPriceTaxMark(pInvoiceDetail.getPriceTaxMark());//含税标志0：不含税 1：含税
                    invoiceDetails.setVatSpecialManagement(pInvoiceDetail.getVatSpecialManagement());
                    invoiceDetails.setFreeTaxMark(pInvoiceDetail.getFreeTaxMark());
                    invoiceDetails.setPreferentialMark(pInvoiceDetail.getPreferential());//是否使用优惠政策 0:未使用，1:使用
                    invoiceDetailsList.add(invoiceDetails);
                }
                request.setInvoiceDetailsList(invoiceDetailsList);
            } else {
                PInvoiceRed pInvoiceRed = (PInvoiceRed) map.get("pInvoiceRed");
                request.setSellerTaxNo(pInvoiceRed.getSellerTaxNo());//销方单位税号
                request.setDeviceType(pInvoiceRed.getDeviceType());//设备类型 0税控服务器，1税控盘
                request.setOrganizationCode(pInvoiceRed.getOrganizationCode());
                request.setSerialNo(pInvoiceRed.getSerialNo());//开票流水号，唯一标志开票请求。支持数字字母下划线组合。
                request.setInvoiceSpecialMark(pInvoiceRed.getInvoiceSpecialMark());//特殊票种标记，00：普通发票 02：农业发票 默认：00
                request.setInvoiceTypeCode(pInvoiceRed.getInvoiceTypeCode());//发票种类编码，004:增值税专用发票，007:增值税普通发票，026：增值税电子发票，025：增值税卷式发票
                request.setInvoiceTerminalCode(pInvoiceRed.getInvoiceYerminalCode());//开票点编码
                request.setBuyerTaxNo(pInvoiceRed.getBuyerTaxNo() == null ? "" : pInvoiceRed.getBuyerTaxNo());//购方单位税号,从前台页面传过来的map中获取
                request.setBuyerName(pInvoiceRed.getBuyerName());//购方单位名称,
                request.setBuyerAddressPhone(pInvoiceRed.getBuyerAddressPhone() == null ? "" : pInvoiceRed.getBuyerAddressPhone());//购方地址及电话专票必填
                request.setBuyerBankAccount(pInvoiceRed.getBuyerBankAccount() == null ? "" : pInvoiceRed.getBuyerBankAccount());//购方开户行及账号专票必填
                request.setDrawer(pInvoiceRed.getDrawer());//开票人
                request.setChecker(pInvoiceRed.getChecker());//复核人
                request.setPayee(pInvoiceRed.getPayee());//收款人
                request.setInvoiceType(FinalUtil.INVOICE_TYPE_RED);//开票类型0:正数发票（蓝票） 1：负数发票（红票）
                request.setInvoiceListMark(pInvoiceRed.getInvoiceListMark());//“清单标志： 0：无清单 1：带清单 （发票明细大于等于8行必须带清单）”
                request.setRedInfoNo(pInvoiceRed.getRedInfoNo());//红字信息表编号专票红冲必填
                request.setOriginalInvoiceCode(pInvoiceRed.getOriginalInvoiceCode());//原发票代码
                request.setOriginalInvoiceNo(pInvoiceRed.getOriginalInvoiceNo());//原发票号码
                request.setTaxationMode(pInvoiceRed.getTaxationMode());//征税方式 0：普通征税，2：差额征税
                request.setDeductibleAmount(pInvoiceRed.getDeductibleAmount());//扣除额保留两位小数
                //request.setInvoiceTotalPrice("-"+MyDateUtil.getTxFloat(pInvoiceRed.getInvoiceTotalPrice()));//合计金额，保留两位小数
                //request.setInvoiceTotalTax("-"+MyDateUtil.getTxFloat(pInvoiceRed.getInvoiceTotalTax()));//合计税额，保留两位小数
                request.setInvoiceTotalPriceTax("-" + MyDateUtil.getTxFloat(pInvoiceRed.getInvoiceTotalPriceTax()));//价税合计，保留两位小数
                request.setSignatureParameter(sCodeNameService.getBWListByType(FinalUtil.CODE_NAME_INVOICE_SIGNATURE_BW).get(0).getCode());//百望所需要的默认签名值
                if (pInvoiceRed.getDeviceType() == "1") {
                    //设备类型为1税控盘，必填
                    request.setTaxDiskNo(pInvoiceRed.getTaxDiskNo());//税控盘编号
                    request.setTaxDiskKey(pInvoiceRed.getTaxDiskKey());//税控盘口令
                    request.setTaxDiskPassword(pInvoiceRed.getTaxDiskPassword());//税务数字证书密码
                }
                request.setGoodsCodeVersion(pInvoiceRed.getGoodsCodeVersion());//商品编码版本号
                request.setConsolidatedTaxRate(pInvoiceRed.getConsolidatedTaxRate());//综合税率
                request.setNotificationNo(pInvoiceRed.getNotificationNo());//通知单编号
                request.setRemarks(pInvoiceRed.getHouseName() == null ? "" : pInvoiceRed.getHouseName() + "/" + pInvoiceRed.getRemarks() == null ? "" : pInvoiceRed.getRemarks());//备注
                //查询开票明细数据

                List<PInvoiceRedDetail> pinvoiceDetailList = pInvoiceRedDetailService.getByInvoiceGuid(pInvoiceRed.getGuid());
                List<InvoiceDetails> invoiceDetailsList = new ArrayList<InvoiceDetails>();
                for (PInvoiceRedDetail pInvoiceDetail : pinvoiceDetailList) {
                    InvoiceDetails invoiceDetails = new InvoiceDetails();
                    invoiceDetails.setGoodsLineNo(pInvoiceDetail.getGoodsLineNo());//明细行号
                    invoiceDetails.setGoodsLineNature(pInvoiceDetail.getGoodsLineNature());//发票行性质，0：正常行 1：折扣行 2：被折扣行
                    invoiceDetails.setGoodsCode(pInvoiceDetail.getGoodsCode());//商品编码
                    invoiceDetails.setGoodsExtendCode(pInvoiceDetail.getGoodsExtendCode());
                    invoiceDetails.setGoodsName(pInvoiceDetail.getGoodsName());//商品名称
                    invoiceDetails.setGoodsTaxItem(pInvoiceDetail.getGoodsTaxItem());
                    invoiceDetails.setGoodsSpecification(pInvoiceDetail.getGoodsSpecification());
                    invoiceDetails.setGoodsUnit(pInvoiceDetail.getGoodsUnit());
                    invoiceDetails.setGoodsQuantity("-" + pInvoiceDetail.getGoodsQuantity());
                    if (!("".equals(pInvoiceDetail.getGoodsPrice()) || pInvoiceDetail.getGoodsPrice() == null)) {
                        invoiceDetails.setGoodsPrice(MyDateUtil.getTxFloat(pInvoiceDetail.getGoodsPrice()));//税额
                    }
                    //  invoiceDetails.setGoodsPrice(MyDateUtil.getTxFloat("".equals(pInvoiceDetail.getGoodsPrice()) || pInvoiceDetail.getGoodsPrice() == null ? "0" : pInvoiceDetail.getGoodsPrice()));
                    if (!("".equals(pInvoiceDetail.getGoodsTotalPrice()) || pInvoiceDetail.getGoodsTotalPrice() == null)) {
                        invoiceDetails.setGoodsTotalPrice("-" + MyDateUtil.getTxFloat(pInvoiceDetail.getGoodsTotalPrice()));//税额
                    }
                    // invoiceDetails.setGoodsTotalPrice("-" + MyDateUtil.getTxFloat("".equals(pInvoiceDetail.getGoodsTotalPrice()) || pInvoiceDetail.getGoodsTotalPrice() == null ? "0" : pInvoiceDetail.getGoodsTotalPrice()));//金额,单位：元，保留两位小数
                    if (!("".equals(pInvoiceDetail.getGoodsTotalTax()) || pInvoiceDetail.getGoodsTotalTax() == null)) {
                        invoiceDetails.setGoodsTotalTax("-" + MyDateUtil.getTxFloat(pInvoiceDetail.getGoodsTotalTax()));//税额
                    }
                    // invoiceDetails.setGoodsTotalTax("-"+MyDateUtil.getTxFloat("".equals(pInvoiceDetail.getGoodsTotalTax())||pInvoiceDetail.getGoodsTotalTax()==null?"0":pInvoiceDetail.getGoodsTotalTax()));//税额
                    invoiceDetails.setGoodsTaxRate(pInvoiceDetail.getGoodsTaxRate());//税率
                    invoiceDetails.setGoodsDiscountLineNo(pInvoiceDetail.getGoodsDiscountLineNo());
                    invoiceDetails.setPriceTaxMark(pInvoiceDetail.getPriceTaxMark());//含税标志0：不含税 1：含税
                    invoiceDetails.setVatSpecialManagement(pInvoiceDetail.getVatSpecialManagement());
                    invoiceDetails.setFreeTaxMark(pInvoiceDetail.getFreeTaxMark());
                    invoiceDetails.setPreferentialMark(pInvoiceDetail.getPreferential());//是否使用优惠政策 0:未使用，1:使用
                    invoiceDetailsList.add(invoiceDetails);
                }
                request.setInvoiceDetailsList(invoiceDetailsList);
            }
        } catch (BopException e) {
            System.out.println(e.getErrCode());
            System.out.println(e.getErrMsg());
            System.out.println(e.getSubMessage());
            System.out.println(e.getSubCode());
            System.out.println(e.getMessage());
        }
        return request;
    }

    /**
     * 获取百望配置信息
     */
    @Override
    public SCodeNameConstant getBwSettingInfo() {
        SCodeNameConstant sCodeNameConstant = new SCodeNameConstant();
        List<SCodeName> a = sCodeNameService.getBWListByType(FinalUtil.CODE_NAME_INVOICE_KEY_BW);
        sCodeNameConstant.setKey(sCodeNameService.getBWListByType(FinalUtil.CODE_NAME_INVOICE_KEY_BW).get(0).getCode());
        sCodeNameConstant.setPassWord(sCodeNameService.getBWListByType(FinalUtil.CODE_NAME_INVOICE_PASSWORD_BW).get(0).getCode());
        sCodeNameConstant.setUesrName(sCodeNameService.getBWListByType(FinalUtil.CODE_NAME_INVOICE_USER_BW).get(0).getCode());
        sCodeNameConstant.setSecret(sCodeNameService.getBWListByType(FinalUtil.CODE_NAME_INVOICE_SECRET_BW).get(0).getCode());
        sCodeNameConstant.setSalt(sCodeNameService.getBWListByType(FinalUtil.CODE_NAME_INVOICE_SALT_BW).get(0).getCode());
        sCodeNameConstant.setRateUrl(sCodeNameService.getBWListByType(FinalUtil.CODE_NAME_INVOICE_URL_BW).get(0).getCode());
        return sCodeNameConstant;
    }
}
